//
// Created by liangzhenying on 16/2/17.
// Copyright (c) 2016 LiangZhenYing. All rights reserved.
//

#import "YLImageViews.h"
#define TagInteger 100
#define kCycleTime 3
#import "UIImageView+WebCache.h"

@interface YLImageViews ()<UIScrollViewDelegate>
@property (nonatomic,assign)BOOL flag;//滚动标识
@property (nonatomic,assign)NSInteger currentPage;//当前的页面
@property (nonatomic,strong)NSTimer *timer;//定时器
@end

@implementation YLImageViews

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (!self) return nil;

    self.pagingEnabled = YES;
    self.scrollEnabled = YES;
    self.delegate = self;
    self.showsHorizontalScrollIndicator = NO;
    self.showsVerticalScrollIndicator = NO;
    self.backgroundColor = [UIColor whiteColor];

    return self;
}

- (void)update {
    
    NSArray *subViews = self.subviews;
    for (UIView *view in subViews) {
        [view removeFromSuperview];
    }
    
    //没有图片
    if (self.urls.count == 0) {
        return;
    }

    //将最后一个加到头部
    NSMutableArray *tempImageArray = [[NSMutableArray alloc] init];
    [tempImageArray addObject:[self.urls lastObject]];
    
    //超过1张图片时，现将所有的图片加进来，再将第一张加到最后一个。例如图片时123456，要实现循环滚动，那么tempImageArray就是61234561
    if (self.urls.count > 1) {
        for (YLImageModel *obj in self.urls) {
            [tempImageArray addObject:obj];
        }
        //将第一个加到尾部
        [tempImageArray addObject:[self.urls objectAtIndex:0]];
    }
    self.urls = tempImageArray;

    //开始添加图片
    for (NSInteger i = 0; i < self.urls.count; i++) {
        YLImageModel *obj = self.urls[i];
        UIImageView *tempImage = [[UIImageView alloc] initWithFrame:CGRectMake(i * self.frame.size.width, 0, self.frame.size.width, self.frame.size.height)];
        [tempImage sd_setImageWithURL:[NSURL URLWithString:obj.imageURL] placeholderImage:nil];
        tempImage.tag = TagInteger + i;
        tempImage.userInteractionEnabled = YES;
        [tempImage addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(click:)]];
        [self addSubview:tempImage];
    }

    //关掉之前的定时器
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;

    }
    
    //超过3张图片时，开启定时器滚动。为什么是>=4张？因为如果原来图片是1张的时候，组装后的self.urls也是1，那么不需要滚动。如果原来图片有两张及以上的时候，组装后的self.urls加了头和尾，所以是4张了，所以你写self.count >= 4 合理些
    if ([self.urls count] >= 4) {
        [self setContentSize:CGSizeMake(self.frame.size.width * [self.urls count], self.frame.size.height)];
        [self setContentOffset:CGPointMake(self.frame.size.width, 0) animated:NO];
        self.timer = [NSTimer scheduledTimerWithTimeInterval:kCycleTime target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    }
}

- (void)click:(UITapGestureRecognizer *)sender {
    UIView *view = sender.view;
    NSInteger index = view.tag - TagInteger;
    YLImageModel *model = self.urls[index];
    [self.imgDelegate imageViews:self didClick:model];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    CGFloat Width = self.frame.size.width;
    if (scrollView.contentOffset.x == self.frame.size.width) {
        self.flag = YES;
    }
    if (self.flag) {
        if (scrollView.contentOffset.x <= 0) {
            //小于0代表滑动到了最左边那个一个，重置到最后一个
            [self setContentOffset:CGPointMake(Width * ([self.urls count] - 2), 0) animated:NO];
        }
        else if (scrollView.contentOffset.x >= Width * ([self.urls count] - 1)) {
            //代表滑动到了最右边那个一个，重置到第一个
            [self setContentOffset:CGPointMake(self.frame.size.width, 0) animated:NO];
        }
    }
    
    int page = scrollView.contentOffset.x / self.frame.size.width - 1;
    [self.imgDelegate imageViews:self showPage:page];
    
    self.currentPage = page + 2 == 2 ? 2 : page + 2;
}

- (void)timerAction {
    //设置滚动到哪一个位置
    [self setContentOffset:CGPointMake(self.frame.size.width * self.currentPage, 0) animated:YES];

    if (self.currentPage > [self.urls count]) {
        //滚动到了最右边，重置会第一个
        self.currentPage = 1;
    } else {
        self.currentPage++;
    }
}

- (void)releaseTimer {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

#pragma mark -UIScrollViewDelegae
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    self.timer = [NSTimer scheduledTimerWithTimeInterval:kCycleTime target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }

}
@end
